package com.example.demo.controller;

import com.example.demo.common.BaseResponse;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.ResultUtils;
import com.example.demo.exception.BusinessException;
import com.example.demo.model.CopyrightTradeRequestInfo;
import com.example.demo.service.CopyrightTradeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 版权交易控制器
 */
@RestController
@RequestMapping("/api/trade")
@CrossOrigin(origins = "*")
public class CopyrightTradeController {
    
    private static final Logger log = LoggerFactory.getLogger(CopyrightTradeController.class);
    
    @Autowired
    private CopyrightTradeService tradeService;
    
    /**
     * 发起交易请求
     * @param fromAddress 发起方地址
     * @param toAddress 接收方地址
     * @param blockchainId 版权ID
     * @param requestType 请求类型：目前仅支持 2-转让
     * @return 交易请求ID
     */
    @PostMapping("/request")
    public BaseResponse<Long> createTradeRequest(
            @RequestParam String fromAddress,
            @RequestParam String toAddress,
            @RequestParam String blockchainId,
            @RequestParam Integer requestType) {
        if (fromAddress == null || fromAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "发起方地址不能为空");
        }
        if (toAddress == null || toAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接收方地址不能为空");
        }
        if (blockchainId == null || blockchainId.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "版权ID不能为空");
        }
        if (requestType == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求类型不能为空");
        }
        
        try {
            Long requestId = tradeService.createTradeRequest(fromAddress, toAddress, blockchainId, requestType);
            return ResultUtils.success(requestId);
        } catch (Exception e) {
            log.error("创建交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 接受交易请求
     * @param requestId 请求ID
     * @param toAddress 接收方地址
     * @return 处理结果
     */
    @PostMapping("/accept")
    public BaseResponse<Boolean> acceptTradeRequest(
            @RequestParam Long requestId,
            @RequestParam String toAddress) {
        if (requestId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求ID不能为空");
        }
        if (toAddress == null || toAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接收方地址不能为空");
        }
        
        try {
            boolean success = tradeService.acceptTradeRequest(requestId, toAddress);
            return ResultUtils.success(success);
        } catch (Exception e) {
            log.error("接受交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接受交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 拒绝交易请求
     * @param requestId 请求ID
     * @param toAddress 接收方地址
     * @param reason 拒绝原因
     * @return 处理结果
     */
    @PostMapping("/reject")
    public BaseResponse<Boolean> rejectTradeRequest(
            @RequestParam Long requestId,
            @RequestParam String toAddress,
            @RequestParam(required = false) String reason) {
        if (requestId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求ID不能为空");
        }
        if (toAddress == null || toAddress.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接收方地址不能为空");
        }
        
        try {
            boolean success = tradeService.rejectTradeRequest(requestId, toAddress, 
                    reason != null ? reason : "用户拒绝");
            return ResultUtils.success(success);
        } catch (Exception e) {
            log.error("拒绝交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "拒绝交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取发起的交易请求
     * @param address 用户地址
     * @return 交易请求列表
     */
    @GetMapping("/sent/{address}")
    public BaseResponse<List<CopyrightTradeRequestInfo>> getSentTradeRequests(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        try {
            List<CopyrightTradeRequestInfo> requests = tradeService.getSentTradeRequests(address);
            return ResultUtils.success(requests);
        } catch (Exception e) {
            log.error("获取发起的交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取发起的交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取收到的交易请求
     * @param address 用户地址
     * @return 交易请求列表
     */
    @GetMapping("/received/{address}")
    public BaseResponse<List<CopyrightTradeRequestInfo>> getReceivedTradeRequests(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        try {
            List<CopyrightTradeRequestInfo> requests = tradeService.getReceivedTradeRequests(address);
            return ResultUtils.success(requests);
        } catch (Exception e) {
            log.error("获取收到的交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取收到的交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取待处理的交易请求
     * @param address 用户地址
     * @return 交易请求列表
     */
    @GetMapping("/pending/{address}")
    public BaseResponse<List<CopyrightTradeRequestInfo>> getPendingTradeRequests(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户地址不能为空");
        }
        
        try {
            List<CopyrightTradeRequestInfo> requests = tradeService.getPendingTradeRequests(address);
            return ResultUtils.success(requests);
        } catch (Exception e) {
            log.error("获取待处理的交易请求失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取待处理的交易请求失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取交易请求详情
     * @param requestId 请求ID
     * @return 交易请求详情
     */
    @GetMapping("/{requestId}")
    public BaseResponse<CopyrightTradeRequestInfo> getTradeRequestDetail(@PathVariable Long requestId) {
        if (requestId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求ID不能为空");
        }
        
        try {
            CopyrightTradeRequestInfo request = tradeService.getTradeRequestDetail(requestId);
            return ResultUtils.success(request);
        } catch (Exception e) {
            log.error("获取交易请求详情失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取交易请求详情失败：" + e.getMessage());
        }
    }
} 